//
//  aRquestModel.m
//  MusicGetPro
//
//  Created by aReu on 2016/11/14.
//  Copyright © 2016年 aReu. All rights reserved.
//

#import "aRquestModel.h"
#import "aRNetworkRequest.h"
#import "API.h"
#import "AFNetworking.h"
#import "aRModel.h"
#import "MJExtension.h"
#import "NeteaseMusicAPI.h"
#import "MBProgressHUD.h"

@implementation aRquestModel

+ (NSDictionary *)dictionaryWithJsonString:(NSData *)data {
    if (data == nil) return nil;
//    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+(void)text{
    NSString *str = @"http://api.xiami.com/api/?api_key=0e4b27543f6179aad9cbfd1fe1fe6d98&api_sig=fd01bd11c4a65530b327977fa8aa190c&call_id=1479708536.420821&is_pub=y&key=明年今日&limit=20&method=Search.summary";
    ;
    [[aRNetworkRequest shareInstance] requestDataToEachPageSetting:^(id object, NSError *error) {
        
    } byRequestUrlString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}


+(void)initializePicByName:(NSString*)name
                 WithBlock:(void (^)(id obj))cb
{
    NSString *urlStr = [NSString stringWithFormat:@"http://starwallpaper.duapp.com?keyword=%@&imgWidth=%@&imgHeight=%@", [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], @(aR_WIDTH * [UIScreen mainScreen].scale), @(aR_HEIGHT * [UIScreen mainScreen].scale)];
    [[aRNetworkRequest shareInstance] requestDataToEachPageSetting:^(id object, NSError *error) {
        if (object[@"data"]) {
            NSMutableArray *mutArr = @[].mutableCopy;
            NSArray *arr = object[@"data"];
            for (NSInteger i = 0; i < arr.count; i++) {
                NSString *str = arr[i][@"image"][@"vip_original"];
                [mutArr addObject:str];
            }
            cb(mutArr);
        }else cb(nil);
    } byRequestUrlString:urlStr];
}


//热门搜索排行
+(void)requestByBillBoardWithBlock:(void (^)(NSMutableArray *arr))cb{
    [[aRNetworkRequest shareInstance] requestDataToEachPageSetting:^(id object, NSError *error) {
        NSMutableArray *mutarr = @[].mutableCopy;
        if (object) {
            NSArray *arr = object[@"data"];
            for (NSDictionary *dic in arr) {
                NSString *str = dic[@"val"];
                [mutarr addObject:str];
            }
            cb(mutarr);
        }
    } byRequestUrlString:kOpenSearchController];
}


+(void)requestQQByName:(NSString*)songName
                 Block:(void (^)(NSMutableArray *arr))cb
{
    aRNetworkRequest *re = [aRNetworkRequest shareInstance];
    NSString *reSr = [[@"http://5even.cc/music.php?do=mis&key=" stringByAppendingString:songName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [re requestDataToEachPageSetting:^(id object, NSError *error) {
        NSMutableArray *arr = [aRModel mj_objectArrayWithKeyValuesArray:object];
        cb(arr?arr:nil);
    } byRequestUrlString:reSr];
}

+(void)requesWangyYunByName:(NSString*)songName
                 Block:(void (^)(NSMutableArray *arr))cb
{
    NeteaseMusicAPICompletionHandler handler = ^(NSData *data, NSURLResponse *response, NSError *error) {
        NSMutableArray *newArr = @[].mutableCopy;
        if (data) {
            NSDictionary *dic = [self dictionaryWithJsonString:data];
            NSArray *arr = dic[@"result"][@"songs"];
            for (NSDictionary *temDic in arr) {
                aRModel *temModel = [aRModel new];
                temModel.pic = temDic[@"album"][@"picUrl"];
                temModel.fMian = temDic[@"album"][@"blurPicUrl"];
                temModel.title = temDic[@"name"];
                temModel.author = temDic[@"artists"][0][@"name"];
                temModel.url = temDic[@"mp3Url"];
                [newArr addObject:temModel];
            }
        }
        cb(newArr);
    };
    [NeteaseMusicAPI searchWithQuery:songName type:NMSearch_Music offset:0 limit:15 completionHandler:handler];
}

//酷狗
+(void)requesKuGouByName:(NSString*)songName
                   Block:(void (^)(NSMutableArray *arr))cb
{
    songName = [songName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *urlStr = [NSString stringWithFormat:@"http://so.ard.iyyin.com/s/song_with_out?page=1&q=%@&size=50",songName];
    aRNetworkRequest *re = [aRNetworkRequest shareInstance];
    [re requestByPOSTWithDic:nil byRequestUrlString:urlStr :^(id object, NSError *error) {
        NSMutableArray *newArr = @[].mutableCopy;
        if (object[@"data"]) {
            NSArray *tempArr = object[@"data"];
            for (NSDictionary *temDic in tempArr) {
                aRModel *temModel = [aRModel new];
                temModel.pic = nil;
                temModel.title = temDic[@"song_name"];
                temModel.author = temDic[@"singer_name"];
                temModel.url = [temDic[@"audition_list"] firstObject][@"url"];
                NSArray *dic = temDic[@"audition_list"];
                NSLog(@"%ld",[tempArr indexOfObject:temDic]);
                if (dic.count > 1) {
                    temModel.mUrl = dic[1][@"url"];
                }
                temModel.hUrl = [temDic[@"audition_list"] lastObject][@"url"];
                if (temDic[@"ll_list"]) {
                    temModel.wuSunUrl = temDic[@"ll_list"][0][@"url"];
                }
                [newArr addObject:temModel];
            }
        }
        cb(newArr);
    }];
}

#pragma mark---伴奏请求下载
//唱吧？？？    5sing
+(void)requesBanzouByName:(NSString*)songName
                   Block:(void (^)(NSMutableArray *arr))cb
{
    songName = [songName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *urlStr = [NSString stringWithFormat:@"http://5sing.shuoba.org/search/search?k=%@&t=0&filterType=1&pn=1&ps=20&sortType=0&version=5.8.0",songName];
    aRNetworkRequest *re = [aRNetworkRequest shareInstance];
    [re requestDataToEachPageSetting:^(id object, NSError *error) {
        if (!object[@"data"]) return;
        NSMutableArray *newArr = @[].mutableCopy;
        NSArray *arr = object[@"data"][@"songArray"];
        for (NSDictionary *temDic in arr) {
            aRModel *temModel = [aRModel new];
            temModel.pic = nil;
            temModel.index = temDic[@"songId"];
            temModel.title = temDic[@"songName"];
            temModel.author = temDic[@"singer"];
            [newArr addObject:temModel];
        }
        cb(newArr);
    } byRequestUrlString:urlStr];
}


+(void)request5SingUrl:(NSString*)songId
                 Block:(void (^)(NSString *str,NSString *head))cb
{
    NSString *urlStr = [NSString stringWithFormat:@"http://mobileapi.5sing.kugou.com/song/newget?songfields=ID,SN,FN,SK,SW,SS,ST,SI,CT,M,S,ZQ,WO,ZC,HY,YG,CK,D,RQ,DD,E,R,RC,SG,C,CS,LV,LG,SY,UID,PT,SCSR,SC&songtype=2&songid=%@&userfields=ID,NN,I",songId];
    aRNetworkRequest *re = [aRNetworkRequest shareInstance];
    [re requestDataToEachPageSetting:^(id object, NSError *error) {
        NSString *banzou = object[@"data"]?object[@"data"][@"KL"]:nil;
        NSString *head = object[@"data"]?object[@"data"][@"user"][@"I"]:nil;
        cb(banzou,head);
    } byRequestUrlString:urlStr];
}


- (void)downFileFromServer:(NSString*)urlString
              CallbackPath:(void(^)(NSURL *aRPath,NSError *error,CGFloat count))callback{
    
    if ([aRquestModel isFileExist:urlString]){
        callback(aRUrl([aRquestModel isFileExist:urlString]),nil,1.0);
        return;
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:aRAPPLICATION.keyWindow animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    NSProgress *progressObject = [NSProgress progressWithTotalUnitCount:100];
    hud.progressObject = progressObject;
    
    NSURLSessionDownloadTask *_downloadTask = nil;
    NSURL *URL                               = [NSURL URLWithString:urlString];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager             = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURLRequest *request                    = [NSURLRequest requestWithURL:URL];
    __block NSString *cathPath                       = nil;
    
    _downloadTask = [manager downloadTaskWithRequest:request
                                            progress:^(NSProgress * _Nonnull downloadProgress)
                     {
                         dispatch_async(dispatch_get_main_queue(), ^{
                             self.countNum = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
//                             CGFloat go = [NSString stringWithFormat:@"%.3f",self.countNum].floatValue;
                         });
                     } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                         
                         debugLog(@"%@",response.suggestedFilename);
                         
                         NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                         cathPath             = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
                         return [NSURL fileURLWithPath:cathPath];
                         
                     } completionHandler:^(NSURLResponse * _Nonnull response,
                                           NSURL * _Nullable filePath,
                                           NSError * _Nullable error)
                     {
                         dispatch_async(dispatch_get_main_queue(), ^{
                             [hud hideAnimated:YES];
                             error? callback(nil,error,self.countNum):callback(filePath,error,0);
                         });
                     }];
    [_downloadTask resume];
}

+(NSString*)isFileExist:(NSString*)fileName{
    NSString *mp3Name = [[[[fileName componentsSeparatedByString:@"/"] lastObject] componentsSeparatedByString:@"?"] firstObject];
    NSString *cathPath   = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:mp3Name];
    return [aRFILE fileExistsAtPath:cathPath]?cathPath:nil;
}

+ (NSArray *)componentsSeparatedFromString:(NSString *)fromString toString:(NSString *)toString  ByStr:(NSString*)tempString{
    if (!fromString || !toString || fromString.length == 0 || toString.length == 0)
        return nil;
    NSMutableArray *subStringsArray = [[NSMutableArray alloc] init];
    NSRange range = [tempString rangeOfString:fromString];
    while (range.location != NSNotFound) {
        tempString =[tempString substringFromIndex:(range.location + range.length)];
        range = [tempString rangeOfString:toString];
        if (range.location != NSNotFound) {
            NSString *str1 = [tempString substringToIndex:range.location];
            [subStringsArray addObject:str1];
            range = [tempString rangeOfString:fromString];
        }else{
            break;
        }
    }
    return subStringsArray;
}



@end
